package cn.itcast.bos.service.impl;

import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.CourierRepository;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.CourierService;

@Service
@Transactional
public class CourierServiceImpl implements CourierService {

	// 注入Dao
	@Autowired
	CourierRepository courierRepository;

	@Override
	public void save(Courier courier) {
		courierRepository.save(courier);
	}
	
	// 无条件的分页查询
	@Override
	public Page<Courier> findPageQuery(Pageable pageable) {
		return courierRepository.findAll(pageable);
	}
	
	// 有条件的分页查询
	@Override
	public Page<Courier> findPageQueryBySpecfication(Pageable pageable,Specification<Courier> spec) {
		return courierRepository.findAll(spec, pageable);
	}
	
	// 快递员删除
	@Override
	public void deleteCourierByIds(String ids) {
		if(StringUtils.isNotBlank(ids)){
			String[] array = ids.split(",");
			for(String id:array){
				courierRepository.updateDelTag(Integer.parseInt(id));
			}
		}
	}
	
	// 查询没有被关联的快递员
	@Override
	public List<Courier> findnoassociation() {
		Specification<Courier> spec = new Specification<Courier>() {
			
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate predicate = cb.isEmpty(root.get("fixedAreas").as(Set.class));
				return predicate;
			}
		};
		return courierRepository.findAll(spec);
	}
	
	// 根据定区ID，查询快递员的集合
	@Override
	public List<Courier> findAssociationCourier(String fixedAreaId) {
		List<Courier> list = courierRepository.findAssociationCourier(fixedAreaId);
		return list;
	}
}
